import React, { useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';
import { authApi } from '../api';

interface AuthGuardProps {
  children: React.ReactNode;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const { isAuthenticated, token, logout, updateAdmin } = useAuthStore();

  useEffect(() => {
    // Verify token validity on app start
    const verifyToken = async () => {
      if (token) {
        try {
          const data = await authApi.getProfile();
          updateAdmin(data);
        } catch (error) {
          console.error('Token verification failed:', error);
          logout();
        }
      }
    };

    verifyToken();
  }, [token, logout, updateAdmin]);

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
};

export default AuthGuard;
